package openjdk.server;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Created by boot on 1/14/16.
 */
public class Cli {
    private String ip;
    private int port;

    public Cli(String ip, int port) throws IOException {
        this.ip = ip;
        this.port = port;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        Cli cli = new Cli("127.0.0.1", 9999);
        //cli.sendMsg("我的好朋友");
        Thread.sleep(2000);
        cli.sendMsgWithNIO("使用NIO测试发送数据：我的朋友");

    }

    public void sendMsg(String msg) {
        try {
            Socket socket = new Socket(ip, port);
            OutputStream os = socket.getOutputStream();
            os.write(msg.getBytes());
            os.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String sendMsgWithNIO(String msg) {
        String rtn = null;
        int len = 0;
        try {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress(ip, port));
//            ByteBuffer buf = ByteBuffer.allocate(1024);
//            buf.clear();
//            buf.put((msg+System.currentTimeMillis()).getBytes());
//            buf.flip();
//            while (buf.hasRemaining()){
//                sc.write(buf);
//            }

            sc.write(ByteBuffer.wrap((msg + System.currentTimeMillis()).getBytes()));
            ByteBuffer buf = ByteBuffer.allocate(1024);
            while ((len = (sc.read(buf))) > 0) {
                buf.flip();
                System.out.println("收到服务器应答:" + Charset.forName(System.getProperty("file.encoding")).decode(buf));
            }

            sc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn;
    }

}
